#!/bin/sh /etc/rc.common
# Copyright (C) 2012-2014 OpenWrt.org

START=90

USE_PROCD=1
PROG="/usr/sbin/easycwmpd"

UCI_SET="/sbin/uci -q ${UCI_CONFIG_DIR:+-c $UCI_CONFIG_DIR} set"
UCI_GET="/sbin/uci -q ${UCI_CONFIG_DIR:+-c $UCI_CONFIG_DIR} get"
UCI_COMMIT="/sbin/uci -q ${UCI_CONFIG_DIR:+-c $UCI_CONFIG_DIR} commit"
init_device_info() {
	local val oval
	local change=0

	val=`cat "/etc/device_info" | grep "DEVICE_MANUFACTURER" | cut -f 2 -d '=' | sed -e "s/['\"]//g" -e "s'[]:@/?#[!$&()*+,;=]'_'g"`
	oval=`$UCI_GET easycwmp.@device[0].manufacturer`
	[ -n "$val" -a "$val" != "$oval" ] && { $UCI_SET easycwmp.@device[0].manufacturer="$val"; change=1; }

	val=`cat "/etc/device_info" | grep "DEVICE_PRODUCT" | cut -f 2 -d '=' | sed -e "s/['\"]//g" -e "s'[]:@/?#[!$&()*+,;=]'_'g"`
	oval=`$UCI_GET easycwmp.@device[0].product_class`
	[ -n "$val" -a "$val" != "$oval" ] && { $UCI_SET easycwmp.@device[0].product_class="$val"; change=1; }

	val=`cat "/etc/device_info" | grep "DEVICE_REVISION" | cut -f 2 -d '=' | sed -e "s/['\"]//g" -e "s'[]:@/?#[!$&()*+,;=]'_'g"`
	oval=`$UCI_GET easycwmp.@device[0].hardware_version`
	[ -n "$val" -a "$val" != "$oval" ] && { $UCI_SET easycwmp.@device[0].hardware_version="$val"; change=1; }

	val=`cat "/etc/openwrt_version"`
	oval=`$UCI_GET easycwmp.@device[0].software_version`
	[ -n "$val" -a "$val" != "$oval" ] && { $UCI_SET easycwmp.@device[0].software_version="$val"; change=1; }
	
	#The same thing here for OUI and SerialNumber

	[ "$change" = "1" ] && $UCI_COMMIT easycwmp
}

start_service() {
	local enable=`uci -q get easycwmp.@local[0].enable`
	if [ "$enable" == "1" ]; then
		init_device_info
		procd_open_instance
		procd_set_param command "$PROG" -f
		if [ "$1" = "--boot" ];then
			procd_append_param command --boot
		else
			procd_append_param command --getrpcmethod
		fi
		procd_set_param respawn "3" "7" "0"
		procd_close_instance
	fi
}

boot() {
	start --boot
}

service_triggers()
{
	procd_add_reload_trigger easycwmp
}
